package fragment.recommendfragments;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;
import com.lanou.horo.myapplication.R;
import com.lanou.horo.myapplication.dbdao.CollectionDBEntity;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;

import dbdao.ColletionDBHelper;
import entity.RecommendDetailsEntity;
import fragment.AbsBaseFragment;
import fragment.tabhostFragment.PersonalDetailsFragment;
import tools.AndroidShare;
import tools.MarqueeTextView;
import utils.adapter.RecomendListAdpter;
import utils.texttools.StringUtil;
import volley.VolleySingleton;

/**
 * 推荐页面 听新闻详情页
 * Created by dllo on 15/11/26.
 */
public class ReCommendDetailsFragment extends AbsBaseFragment implements View.OnClickListener {
    private RecomendListAdpter listAdpter;
    private ListView lv;
    private LinearLayout inivs, tv, stuck_action;
    private RelativeLayout heardRelat;

    private TextView albun_collection, album_down, recomemd, collection_action, textDp, renickName,
            recomdplaytimes, recommendHeardIntro, recommendHeardTargs, recomdTotalCount;
    private long aid, trackId,uesid,albumId;
    private int positon, count = 0;
    private ImageView recomedBack, share;
    private MarqueeTextView recomTitle;
    private NetworkImageView headrIv, smallIv, recomendBigImg;
    private View heard, action;//定义一个头布局



    private ColletionDBHelper dBhelper;


    private List<RecommendDetailsEntity.TracksEntity.ListEntity> listEntity;
    private String path, name, imgUri, title,image;


    @Override
    protected int getLayoutView() {
        return R.layout.fragment_details_recommend;
    }

    @Override
    protected void initView() {
        albun_collection = findView(R.id.albun_collection);//收藏
        recomdTotalCount = findView(R.id.recomdTotalCount);
        recomedBack = findView(R.id.recomedBack);
        renickName = findView(R.id.renickName);
        recomendBigImg = findView(R.id.recomendBigImg);
        smallIv = findView(R.id.smallIv);
        recomTitle = findView(R.id.recomTitle);
        recomdplaytimes = findView(R.id.recomdplaytimes);
        inivs = findView(R.id.invis);
        recomemd = findView(R.id.recomemd);
        lv = findView(R.id.lv);
        listEntity = new ArrayList<>();
        dBhelper = ColletionDBHelper.getInstance();
    }

    public ReCommendDetailsFragment(long aid, int positon) {
        this.aid = aid;
        this.positon = positon;
    }


    @Override
    protected void initData() {

        recomemd.setOnClickListener(this);
        albun_collection.setOnClickListener(this);


        lv.setVerticalScrollBarEnabled(true);
        //悬浮部分
        action = View.inflate(getContext(), R.layout.recommend_stuck_action, null);
        //头部内容
        heard = View.inflate(getContext(), R.layout.recommend_stick_heard, null);

        //初始化头布局的空间
        heard.findViewById(R.id.recomedBack).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goBack();
            }
        });
        heard.findViewById(R.id.share).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//分享的点击
//                Intent intent = new Intent(Intent.ACTION_SEND);
//                intent.setType("text/plain");
//                intent.putExtra(Intent.EXTRA_TEXT, "O(∩_∩)O哈哈~我正在听珠穆拉玛FM："
//                        + name + "," + "点击:" + path + "一起来收听吧(*^__^*) ");
//                startActivity(intent);
                AndroidShare as = new AndroidShare(
                        getActivity(),
                        "我正在用珠穆朗玛收听:" + name + "点击" + path + "一起收听",
                        image);
                as.show();
            }
        });

        heard.findViewById(R.id.smallIv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToNext(new PersonalDetailsFragment(uesid));

            }
        });
        lv.addHeaderView(heard);
        lv.addHeaderView(action);
        lv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem >= 1) {
                    //悬浮部分
                    inivs.setVisibility(View.VISIBLE);
                } else {
                    inivs.setVisibility(View.GONE);
                }
            }
        });

        //行监听
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (position > 1) {
                    trackId = listEntity.get(position - 2).getTrackId();
                    goToPlay(trackId);
                }

            }
        });

        initNetwork();
        listAdpter = new RecomendListAdpter();
        lv.setAdapter(listAdpter);

        //强转
        ((TextView)  action.findViewById(R.id.recomend)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToNext(new Recomendaboutfragment(albumId));
            }
        });
        ((LinearLayout) action.findViewById(R.id.linearListener)).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (count == 0) {
                    ((TextView) action.findViewById(R.id.collection_action)).
                            setText("已收藏");
                    albun_collection.setText("已收藏");
                    savaData();
                    count = 1;
                } else {
                    ((TextView) action.findViewById(R.id.collection_action)).
                            setText("收藏");
                    albun_collection.setText("收藏");
                    cancel();
                    count = 0;
                }

            }
        });


    }




    private void initNetwork() {
        String URL = "http://mobile.ximalaya.com/mobile/others/ca/album/track/" +
                aid + "/true/1/20?&albumId=" + aid + "&isAsc=true&device=android&pageSize=100";
        VolleySingleton.getInstance().addRequest(URL,
                RecommendDetailsEntity.class, new Response.Listener<RecommendDetailsEntity>() {
                    @Override
                    public void onResponse(RecommendDetailsEntity response) {
                        if (response != null) {
                            RecommendDetailsEntity.AlbumEntity album = response.getAlbum();
                            VolleySingleton.getInstance().getBitmap(album.getCoverLarge(), (NetworkImageView) heard.findViewById(R.id.stickHeadBg));

                            if (album != null) {
                                ((TextView) heard.findViewById(R.id.recomdplaytimes)).setText(StringUtil.longToWan(album.getPlayTimes()));
                                ((TextView) heard.findViewById(R.id.renickName)).setText(album.getNickname());
                                ((TextView) heard.findViewById(R.id.recomTitle)).setText(album.getTitle());
                                ((TextView) heard.findViewById(R.id.recommendHeardIntro)).setText(album.getIntro());
                                ((TextView) heard.findViewById(R.id.recommendHeardTargs)).setText(album.getTags());
                                albumId= album.getAlbumId();

                                VolleySingleton.getInstance().getBitmap(album.getCoverSmall(),
                                        ((NetworkImageView) heard.findViewById(R.id.smallIv)));
                                VolleySingleton.getInstance().getBitmap(album.getCoverMiddle(),
                                        ((NetworkImageView) heard.findViewById(R.id.recomendBigImg)));
                            }
                            RecommendDetailsEntity.TracksEntity tra = response.getTracks();
                            if (tra != null) {
                                recomdTotalCount.setText("共" + tra.getTotalCount() + "集");
                                ((TextView) action.findViewById(R.id.stuckTotalCount)).setText("共"
                                        + tra.getTotalCount() + "集");
                                listEntity = response.getTracks().getList();
                                if (listEntity != null) {
                                    listAdpter.addData(listEntity);
                                    path = listEntity.get(positon).getPlayPathAacv164();
                                    name = listEntity.get(positon).getAlbumTitle();
                                    uesid = listEntity.get(positon).getUid();
                                    image = listEntity.get(positon).getSmallLogo();



                                }
                            }
                            dismissDialog();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        dismissDialog();
                        toastError();
                    }
                });
        showDialog();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.albun_collection:
                colletion();
                break;
            case R.id.recomemd:
                goToNext(new Recomendaboutfragment(aid));
                break;
        }
    }

    private void colletion() {
        if (count == 0) {
            albun_collection.setText("已收藏");
            ((TextView) action.findViewById(R.id.collection_action)).
                    setText("已收藏");
            savaData();
            count = 1;
        } else if (count == 1) {
            albun_collection.setText("收藏");
            ((TextView) action.findViewById(R.id.collection_action)).
                    setText("收藏");

            cancel();
            count = 0;
        } else {

        }
    }

    private void savaData() {


        List<CollectionDBEntity> datas = new ArrayList<>();
        CollectionDBEntity entity = new CollectionDBEntity();
        entity.setNickname(listEntity.get(positon).getNickname());
        entity.setSmallLogo(listEntity.get(positon).getSmallLogo());
        entity.setPlayUrl(listEntity.get(positon).getPlayUrl32());
        entity.setTrackId(listEntity.get(positon).getTrackId());
        entity.setAlbmid(listEntity.get(positon).getAlbumId());
        entity.setTitle(listEntity.get(positon).getAlbumTitle());
        long id = listEntity.get(positon).getTrackId();
//      if (dBhelper.queryAll() != null&&dBhelper.queryAll().size()>0){
//          if (dBhelper.querById(id)!=null&& dBhelper.querById(id).size()>0){//如果存在id
//              dBhelper.updateByName(id);
//          }
//      }else {}

        if (dBhelper.querById(id).size() == 0 || dBhelper.querById(id) == null) {
            datas.add(entity);
            dBhelper.saveHost(datas);
        } else {
            Toast.makeText(getContext(), "您已经收藏过了", Toast.LENGTH_SHORT).show();
        }

    }

    private void cancel() {
        ColletionDBHelper.getInstance().deleById(listEntity.get(positon).getTrackId());
    }

}
